package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;

import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;


    public void deleteByPrimaryKey(Long id) {
        if (id != null) {

            menuMapper.deleteByPrimaryKey(id);
        }
    }

    @Override

    public void saveOrUpdate(Menu record) {
        if (record.getId() != null) {
            //update
            menuMapper.updateByPrimaryKey(record);
        }else {
            menuMapper.insert(record);
        }
    }

    @Override
    public Menu selectByPrimaryKey(Long id) {

        Menu dept = menuMapper.selectByPrimaryKey(id);
        return dept;

    }
    @Override
    //根据不同用户分配不同的菜单
    public List<Menu> queryAllMenu() {
        List<Menu> menus = menuMapper.queryAllMenu();
        Employee user = UserContext.getCurrentUser();
        if (user.isAdmin()) {
            return  menus;
        }
        //通过当前用户查询已有的菜单id,封装成一个数组
      List<Long> menuIds =  menuMapper.selectMenuByEmployeeId(user.getId());
      checkMenu(menus,menuIds);
        return menus;
    }

    private void checkMenu(List<Menu>menus, List<Long> ids){
        Iterator<Menu> it = menus.iterator();
        while (it.hasNext()) {
            Menu menu = it.next();
            if (!ids.contains(menu.getId())) {
                it.remove();
            }
            if (menu.getChildren()!=null){
                checkMenu(menu.getChildren(),ids);
            }
        }

    }

    @Override
    //查询出所有的顶级菜单
    public List<Menu> getMenusNoSon() {
        List<Menu> menus = menuMapper.getMenusNoSon();

        return menus;
    }

    @Override
    //通过id查询子菜单
    public List<Menu>  getMenusByParentId(Long id) {

        return menuMapper.getMenusByParentId(id);
    }

    public PageResult queryForList(QueryObject qo) {
        int rows = menuMapper.rows(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result =  new PageResult(rows,menuMapper.queryForList(qo));
        return result;
    }

}
